package com.wg.dome.handle;

import com.wg.dome.ClientPeer;
import com.wg.dome.ErrorCode;
import com.wg.dome.ErrorHelper;
import com.wg.dome.entity.user.HeroEntity;
import com.wg.dome.operation.BuZhenRequest;
import com.wg.dome.operation.BuZhenResponse;
import com.wg.dome.repository.HeroRepositoryEx;
import com.wg.core.net.OperationRequest;
import com.wg.core.net.OperationResponse;
import com.wg.core.net.SendParameters;

/**
 * 布阵
 */
public class HandleRequest7 extends BaseHandle {

    @Override
    public OperationResponse execute(ClientPeer peer, OperationRequest request, SendParameters sendParameters) {
        BuZhenRequest buZhenRequest = new BuZhenRequest(request);
        if (!buZhenRequest.isValid()) {
            return ErrorHelper.getInvalidResponse(buZhenRequest);
        }

        if (buZhenRequest.getPlayerId() != peer.getPlayerId()) {
            return ErrorHelper.getErrorResponse(request.getOperationCode(),
                    ErrorCode.PLAYERID_MATCH_ERROR, buZhenRequest.getPlayerId(), peer.getPlayerId());
        }

        HeroRepositoryEx heroRepository = new HeroRepositoryEx(peer.getPlayerId());
        HeroEntity heroEntity = heroRepository.getEntityFromFight(buZhenRequest.getHeroId());
        if (heroEntity == null) {
            return ErrorHelper.getErrorResponse(request.getOperationCode(), ErrorCode.FIGHT_HEROID_ERROR, buZhenRequest.getHeroId());
        }

        HeroEntity srcHeroEntity = heroRepository.getEntityBySzPos(buZhenRequest.getPos());
        if (srcHeroEntity != null) {
            srcHeroEntity.setBzPos(heroEntity.getBzPos());
            heroRepository.update(srcHeroEntity);
        }
        heroEntity.setBzPos(buZhenRequest.getPos());
        heroRepository.update(heroEntity);

        BuZhenResponse buZhenResponse = new BuZhenResponse();
        buZhenResponse.setRoleMapArray(heroRepository.getBzHashTables());
        return new OperationResponse(request.getOperationCode(), buZhenResponse);
    }
}
